package com.szrt.ch04.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.szrt.ch04.entity.UserEntity;

public class UserController extends HttpServlet {
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//		System.out.println("进入servlet");
//		System.out.println(req.getParameter("nameuser"));
//		
////		int counter=service.add(UserEntity entity);
//		//如何返回一个数据给前台
//		
//		
//		//固定的套路
//		resp.setContentType("text/html;charset=utf-8");
//		
//		PrintWriter writer = resp.getWriter();
//		
//		//影响的记录行数 1/0
//		//插入成功 
//		Map<String,String> jieguo=new HashMap<String,String>();
//		jieguo.put("couter", "1");
//		jieguo.put("message", "插入成功...");
//		
//		Gson json=new Gson();
//		String jsonString = json.toJson(jieguo);
//		
//		writer.write(jsonString);
		
		
		
		//根据请求的不同调用不同的方法
		String method=req.getParameter("method");
		
		if("getPalyCoin".equals(method)){
			getPalyCoin(req,resp);
//			不结束会
			return;
		}
	}
	
	public void getPalyCoin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		req.setCharacterEncoding("utf-8");
//		凡是http协议传送的数据只有一种类型 字符串
		String age = req.getParameter("age");
		String playCoin="";
		if(Integer.parseInt(age)>=18){
			playCoin="500";
		}else{
			playCoin="100";
		}
		System.out.println(playCoin);
		
		UserEntity user=new UserEntity();
		
		user.setId(1);
		user.setPhone("123");
		user.setPassword("123abc");
		
		
		//写到response
		
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		Map<String,Object> jieguo=new HashMap<String,Object>();
		jieguo.put("playCoin",playCoin);
		jieguo.put("message", "请求成功...");
		jieguo.put("user", user);
		
		Gson json=new Gson();
		String jsonString = json.toJson(jieguo);
		
		writer.write(jsonString);
	}
	
	

}
